import datetime
import time
from typing import Optional

from sqlalchemy import String
from sqlalchemy.orm import Session

from app.db import DbOper
from app.db.models.archive import Archive


class ArchiveOper(DbOper):
    """
    消息数据管理
    """

    def __init__(self, db: Session = None):
        super().__init__(db)

    def add(self,
            title: str = None,
            title_display: str = None,
            thumb: str = None,
            upload_time: str = None,
            upload_by: str = None,
            file_name: str = None,
            file_path: str = None,
            file_size: int = None,
            url: str = None,
            unpack_path: str = None,
            pages: int = None,
            progress: int = 0,
            md5: str = None,
            categories_id: str = None,
            tags_id: str = None,
            **kwargs) -> int:
        """
        新增档案数据
        :param title: 标题
        :param title_display: 标题(显示)
        :param thumb: 缩略图
        :param upload_time: 上传时间
        :param upload_by: 上传人
        :param file_name: 文件名
        :param file_path: 文件路径
        :param file_size: 文件大小
        :param url: 源地址url
        :param unpack_path: 解压路径
        :param pages: 总页数
        :param progress: 阅读进度
        :param md5: 文件md5
        :param categories_id: 分类ID
        :param tags_id: 标签ID列表
        """
        kwargs.update({
            "title": title,
            "title_display": title_display,
            "thumb": thumb,
            "upload_time": upload_time,
            "upload_by": upload_by,
            "file_name": file_name,
            "file_path": file_path,
            "file_size": file_size,
            "url": url,
            "md5": md5,
            "categories_id": categories_id,
            "tags_id": tags_id,
            "add_time": datetime.datetime.now(),
            "unpack_path": unpack_path,
            "is_new": 1,
            "pages": pages,
            "progress": progress,
        })
        return Archive(**kwargs).create_get_id(self._db)

    def get_by_title(self, title: String) -> Optional[Archive]:
        """
        根据ID查询档案
        """
        return Archive.get_by_title(id)

    def update(self, archive_id: int, payload) -> Archive:
        """
        更新档案
        """
        archive = Archive.get(self._db, archive_id)
        archive.update(self._db, payload)
        return archive

    def list_by_page(self, page: int = 1, count: int = 30) -> Optional[str]:
        """
        查询档案分页列表
        """
        return Archive.list_by_page(self._db, page, count)
